/**
 * 
 */
package org.mspring.mlog.web.module.web.plugin;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.entity.Comment;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.CommentService;
import org.mspring.mlog.service.OptionService;
import org.mspring.mlog.utils.CommentCacheUtils;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用于评论Widget的数据准备
 * 
 * @author Gao Youbo
 * @since 2013年6月26日
 */
@Widget
@RequestMapping("/plugin/comment")
public class Plugin_CommentWidget extends Plugin_AbstractWidget {
    @Autowired
    private CommentService commentService;

    @Autowired
    private OptionService optionService;

    /**
     * 渲染评论框，并返回渲染后的网页内容
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/form")
    @ResponseBody
    public String form(HttpServletRequest request, HttpServletResponse response) {
        User user = SecurityUtils.getCurrentUser(request);
        Map<Object, Object> model = new HashMap<Object, Object>();
        model.put("base", request.getContextPath());
        model.put("user", user);
        return render(request, "/plugin/comment/comment-form.ftl", model);
    }

    /**
     * 渲染评论列表，并返回渲染后的网页内容
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public String list(HttpServletRequest request, HttpServletResponse response) {
        String fkey = RequestUtils.getRequestParameterAsString(request, "fkey");
        String ftype = RequestUtils.getRequestParameterAsString(request, "ftype");
        if (fkey == null || ftype == null) {
            return "";
        }
        Integer page = RequestUtils.getRequestParameterAsInteger(request, "page");
        if (page == null) {
            page = 1;
        }

        // 从缓存中获取
        String result = CommentCacheUtils.getCachedCommentList(fkey, ftype, page);
        if (StringUtils.isNotBlank(result)) {
            return result;
        }

        Page<Comment> commentPage = commentService.findComment(ftype, fkey, page);
        Map<Object, Object> model = new HashMap<Object, Object>();
        model.put("base", request.getContextPath());
        model.put("user", SecurityUtils.getCurrentUser(request));
        model.put("comments", commentPage.getResult());
        model.put("pageNo", commentPage.getPageNo());
        model.put("pageSize", commentPage.getPageSize());
        model.put("totalCount", commentPage.getTotalCount());
        model.put("totalPage", commentPage.getTotalPages());
        result = render(request, "/plugin/comment/comment-list.ftl", model);
        // try {
        // result = HtmlCompressor.compress(result);
        // } catch (Exception e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }

        // 添加缓存
        CommentCacheUtils.setCachedCommentList(fkey, ftype, page, result);

        return result;
    }

    /**
     * 发表评论
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public ResponseEntity addCmt(HttpServletRequest request, HttpServletResponse response) {
        ResponseEntity rsp = new ResponseEntity();

        // 验证用户是否登录
        User user = SecurityUtils.getCurrentUser(request);
        if (user == null) {
            rsp.setSuccess(false);
            rsp.setMessage("请先登录后再评论");
            return rsp;
        }

        // 准备评论数据
        String ip = RequestUtils.getRemoteIP(request);
        String userAgent = RequestUtils.getUserAgent(request);
        String content = RequestUtils.getRequestParameterAsString(request, "content");
        Long parent = RequestUtils.getRequestParameterAsLong(request, "parent");
        String fkey = RequestUtils.getRequestParameterAsString(request, "fkey");
        String ftype = RequestUtils.getRequestParameterAsString(request, "ftype");
        Long toUser = RequestUtils.getRequestParameterAsLong(request, "toUser");
        String status = Comment.Status.APPROVED;
        String is_comment_audit = optionService.getOption("comment_audit");
        if ("true".equals(is_comment_audit)) {
            status = Comment.Status.WAIT_FOR_APPROVE;
        }

        // 验证数据
        if (toUser == null) {
            rsp.setSuccess(false);
            rsp.setMessage("评论失败，无法确定toUser参数");
            return rsp;
        }
        if (StringUtils.isBlank(fkey)) {
            rsp.setSuccess(false);
            rsp.setMessage("评论框配置错误，请确认参数f_key是否正确配置");
            return rsp;
        }
        if (StringUtils.isBlank(ftype)) {
            rsp.setSuccess(false);
            rsp.setMessage("评论框配置错误，请确认参数f_type是否正确配置");
            return rsp;
        }
        if (StringUtils.isBlank(content)) {
            rsp.setSuccess(false);
            rsp.setMessage("请输入评论内容");
            return rsp;
        }

        // 构建评论对象
        Comment cmt = new Comment();
        cmt.setAuthor(user);
        cmt.setContent(content);
        cmt.setPostIp(ip);
        cmt.setAgent(userAgent);
        cmt.setFkey(fkey);
        cmt.setFtype(ftype);
        cmt.setStatus(status);
        cmt.setToUser(new User(toUser));
        if (parent != null) {
            cmt.setParent(new Comment(parent));
        }

        // 持久化
        cmt = commentService.save(cmt);
        rsp.setSuccess(true);
        rsp.setMessage("评论发表成功");
        rsp.put("cmt", cmt);
        return rsp;
    }
}